import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:open_source_china/api/user.dart';
import 'package:open_source_china/constants/size_list.dart';
import 'package:open_source_china/constants/constants.dart';
import 'package:open_source_china/model/user.dart';
import 'package:open_source_china/pages/LoginPage/LoginPage.dart';
import 'package:open_source_china/pages/ProfileDetailPage/ProFileDetailPage.dart';
import 'package:open_source_china/utils/DataUtils.dart';
import 'package:open_source_china/utils/EventBus.dart';
import 'package:open_source_china/widget/avatar.dart';

class MinePage extends StatefulWidget {
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  List menuTitles = ["我的消息", "阅读记录", "我的博客", "我的问答", "我的活动", "我的团队"];
  List menuIcons = [
    Icons.message,
    Icons.print,
    Icons.error,
    Icons.send,
    Icons.people,
    Icons.person
  ];
  User user;

  @override
  void initState() {
    // TODO: initState
    super.initState();
    showUserInfo();
    // 监听登录和登出
    eventBus.on<LoggedEvent>().listen((event) {
      showUserInfo();
    });
    eventBus.on<LogoutEvent>().listen((event) {
      showUserInfo();
    });
  }

  /// 尝试展示用户信息
  showUserInfo() async {
    if (mounted) {
      UserApi.getInfo().then((user) {
        print(user);
        setState(() {
          this.user = user;
        });
      });
    }
  }

  /// 登录
  login() async {
    await DataUtils.logout();
    final String result = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => LoginPage()));
    if (result != null && result == AppMsg.SUCCESS) {
      eventBus.fire(LoggedEvent());
    }
  }

  @override
  Widget build(BuildContext context) {
    // debugPaintSizeEnabled = true;
    return ListView.separated(
        itemBuilder: (context, index) {
          if (index == 0) {
            return buildHeader();
          }
          index--;
          return ListTile(
              leading: Icon(menuIcons[index]),
              title: Text(menuTitles[index]),
              trailing: Icon(Icons.arrow_forward_ios));
        },
        separatorBuilder: (context, index) {
          double height = index == 0 ? 0 : 1;
          return Divider(
            height: height,
          );
        },
        itemCount: menuTitles.length + 1);
  }

  /// 构建头部
  GestureDetector buildHeader() {
    return GestureDetector(
      onTap: () async {
        bool islogin = await DataUtils.hasLogin();
        if (islogin) {
          // TODO: 跳转到用户详情
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => ProfileDetail(user.id)));
        } else {
          login();
        }
      },
      child: Container(
        height: SizeList.MinePage_HEAD_HEIGHT,
        alignment: Alignment.center,
        color: Theme.of(context).primaryColor,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: SizeList.AVATAR_SIZE,
              height: SizeList.AVATAR_SIZE,
              // ClipRRect 实现圆角切割
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(SizeList.AVATAR_SIZE / 2),
                  child: Avatar(path: user?.avatar)),
            ),
            SizedBox(
              height: SizeList.S_B_1,
            ),
            Text(
              user?.name ?? "点击头像登录",
              style: TextStyle(color: Colors.white),
            )
          ],
        ),
      ),
    );
  }
}
